package com.example.oauth2demo.interceptor;

import com.example.oauth2demo.config.GiteeOauthConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author karidyang
 * @since 1.0.0
 * Date: 2021-04-19
 *
 **/
@Component
public class AuthInterceptor implements HandlerInterceptor {
    private final static String AUTH_URL = "https://gitee.com/oauth/authorize?client_id=%s&redirect_uri=%s&response_type=code";
    @Autowired
    private GiteeOauthConfig giteeOauthConfig;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        final HttpSession session = request.getSession();
        Object token = session.getAttribute("token");
        if (token == null) {
            final String url = String.format(AUTH_URL, giteeOauthConfig.getClientId(), giteeOauthConfig.getRedirectUri());
            System.out.println(url);
            response.sendRedirect(url);
            return false;
        }
        return true;

    }
}
